package com.zh.note.demo.juc;

import lombok.Getter;
import lombok.Setter;

import java.util.Random;
import java.util.concurrent.CountDownLatch;

/**
 * @Author: zhanghuan
 * @date: 2025/8/24 23:36
 * @description: create it
 */


/**
 * 资源类
 */
class SU7 {
    @Setter
    @Getter
    private int saleTotal;

    public synchronized void saleTotal() {
        saleTotal++;
    }

    // ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>() {
    //     @Override
    //     protected Integer initialValue() {
    //         return 0;
    //     }
    // };

    ThreadLocal<Integer> threadLocal = ThreadLocal.withInitial(() -> 0);

    public void salePersonal() {
        threadLocal.set(1 + threadLocal.get());
    }
}

public class ThreadLocalDemo {
    public static void main(String[] args) throws InterruptedException {
        SU7 su7 = new SU7();
        CountDownLatch countDownLatch = new CountDownLatch(3);
        for (int i = 0; i < 3; i++) {
            new Thread(() -> {
                try {
                    for (int j = 1; j <= new Random().nextInt(3) + 1; j++) {
                        su7.saleTotal();
                        su7.salePersonal();
                    }
                    System.out.println(Thread.currentThread().getName() + "\t" + "销售卖出：" + su7.threadLocal.get());
                } finally {
                    countDownLatch.countDown();
                    su7.threadLocal.remove();
                }
            }, String.valueOf(i)).start();
        }
        countDownLatch.await();
        System.out.println(Thread.currentThread().getName() + "--> 总额： " + su7.getSaleTotal());

    }
}
